<template>
<!-- 慢病证管理 -->
  <div class="chronic-disease-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="疾病名称"> <!-- 修改为疾病名称 -->
              <el-input
                v-model="searchForm.diseaseName" 
                placeholder="请输入疾病名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮（保持不变） -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增慢病证
      </el-button>
    </div>

    <!-- 慢病证列表（保持不变） -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px; display: flex;"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <!-- 表格列保持不变 -->
      <el-table-column prop="certificateId" label="慢病证ID" width="120" align="center" />
      <el-table-column prop="farmerName" label="农民姓名" width="180" show-overflow-tooltip />
      <el-table-column prop="diseaseName" label="疾病名称" width="180" show-overflow-tooltip />
      <el-table-column label="确诊时间" width="180" align="center">
        <template #default="{ row }">
          {{ formatDate(row.startTime, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="有效期至" width="180" align="center">
        <template #default="{ row }">
          {{ formatDate(row.endTime, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（保持不变） -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 新增/编辑对话框（保持不变） -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="农民ID" prop="farmerId">
          <el-input v-model.number="formData.farmerId" placeholder="请输入农民ID" />
        </el-form-item>
        
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input v-model="formData.diseaseName" placeholder="请输入疾病名称" /> <!-- 保持不变 -->
        </el-form-item>
        
        <el-form-item label="确诊时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="date"
            placeholder="选择确诊日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="有效期截止时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="date"
            placeholder="选择截止日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate as dateFormat } from '@/utils/dateUtil'

export default {
  name: 'ChronicDiseaseManagement',
  data() {
    return {
      searchForm: { 
        diseaseName: '' // 修改为 diseaseName 字段
      },
      tableData: [],
      loading: false,
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      dialogVisible: false,
      dialogTitle: '新增慢病证',
      formData: {
        certificateId: null,
        farmerId: null,
        diseaseName: '',
        startTime: null,
        endTime: null
      },
      formRules: {
        farmerId: [{ required: true, message: '请输入农民ID', trigger: 'blur' }],
        diseaseName: [{ required: true, message: '请输入疾病名称', trigger: 'blur' }], // 保持不变
        startTime: [{ required: true, message: '请选择确诊时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择有效期截止时间', trigger: 'change' }]
      }
    }
  },
  computed: {
    isEdit() { return !!this.formData.certificateId }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 日期格式化（保持不变）
    formatDate(date, format) {
      return date ? dateFormat(date, format) : '--'
    },

    // 数据加载（修改查询参数为 diseaseName）
    fetchData() {
      this.loading = true
      const queryParam = {
        diseaseName: this.searchForm.diseaseName // 传递疾病名称参数
      }

      request.post('/chronicDiseaseCertificate/query', queryParam, {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize
        }
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records.map(item => ({
            ...item,
            startTime: new Date(item.startTime),
            endTime: new Date(item.endTime)
          }))
          this.pagination.total = res.data.total
        } else {
          ElMessage.error(res.message || '数据加载失败')
        }
      }).catch(err => {
        ElMessage.error('网络请求失败')
        console.error(err)
      }).finally(() => this.loading = false)
    },

    // 搜索相关方法（保持逻辑不变）
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm.diseaseName = '' // 清空疾病名称
      this.handleSearch()
    },

    // 分页、新增、编辑、删除方法（全部保持不变）
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增慢病证'
      this.resetForm()
      this.formData.startTime = new Date()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑慢病证'
      this.formData = {
        ...row,
        startTime: new Date(row.startTime),
        endTime: new Date(row.endTime)
      }
      this.dialogVisible = true
    },
    handleDelete(row) {
      ElMessageBox.confirm(`确认删除慢病证 ${row.certificateId}？`, '提示', {
        type: 'warning'
      }).then(() => {
        return request.post(`/chronicDiseaseCertificate/delete/${row.certificateId}`)
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.fetchData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      }).catch(err => {
        ElMessage.error('操作取消')
      })
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const apiUrl = this.isEdit ? '/chronicDiseaseCertificate/update' : '/chronicDiseaseCertificate/create'
        const formData = {
          ...this.formData,
          startTime: this.formatDate(this.formData.startTime, 'YYYY-MM-DD'),
          endTime: this.formatDate(this.formData.endTime, 'YYYY-MM-DD')
        }

        request.post(apiUrl, formData).then(res => {
          if (res.code === 200) {
            ElMessage.success(`${this.dialogTitle}成功`)
            this.dialogVisible = false
            this.fetchData()
          } else {
            ElMessage.error(res.message || `${this.dialogTitle}失败`)
          }
        })
      })
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = { 
        certificateId: null,
        farmerId: null,
        diseaseName: '',
        startTime: null,
        endTime: null 
      }
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.chronic-disease-container { padding: 20px; background: #fff; }
.search-container { margin-bottom: 20px; padding: 20px; background: #f5f7fa; border-radius: 4px; }
.operation-buttons { display: flex; gap: 10px; margin-bottom: 20px; }
.el-table { font-size: 14px; margin-top: 15px !important; }
.el-table th { background: #f5f7fa; font-weight: 500; }
.pagination-container { margin-top: 30px; text-align: right; }
.el-table { display: table; }
</style>